package com.yeqiangwei.commons.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author aroot
 *
 */
public class ZipHelper {
	
	private static final Log log = LogFactory.getLog(ZipHelper.class);

	public final static boolean zip(String zipfile, File srcDir) {
		Boolean bea = false;
		try {
			FileOutputStream f = new FileOutputStream(zipfile);
			ZipOutputStream out = new ZipOutputStream(new DataOutputStream(f));
			zipFile(out, zipfile, srcDir, null);
			out.flush();
			out.close();
			bea = true;
		} catch (IOException e) {
			log.error(e.toString());
		}
		return bea;
	}
	
	/**
	 * 
	 * @param zipfile
	 * @param srcDir
	 * @param basePath 压缩包内文件存放的路径
	 * @return
	 */
	public final static boolean zip(String zipfile, File srcDir, String basePath) {
		Boolean bea = false;
		try {
			FileOutputStream f = new FileOutputStream(zipfile);
			ZipOutputStream out = new ZipOutputStream(new DataOutputStream(f));
			zipFile(out, zipfile, srcDir, null);
			out.flush();
			out.close();
			bea = true;
		} catch (IOException e) {
			log.error(e.toString());
		}
		return bea;
	}
	
	/**
	 * 
	 * @param out
	 * @param srcDir
	 * @param basePath 压缩包内文件存放的路径
	 * @throws IOException
	 */
	private static final void zipFile(ZipOutputStream out
			, String zipfile, File srcDir, String basePath)	throws IOException 
	{
		if(srcDir.isFile()){
			FileInputStream in = new FileInputStream(srcDir);
			if(basePath != null){
				out.putNextEntry(new ZipEntry(basePath + File.separator + srcDir.getName()));
			} else {
				out.putNextEntry(new ZipEntry(srcDir.getName()));
			}
			byte[] b = new byte[1024];
			int byteread = 0;
			int bytesum = 0;
			int off = 0;
			while ((byteread = in.read(b, off, 1024)) != -1) {
				bytesum += byteread; // 字节数 文件大小
				out.write(b, 0, byteread);
			}
			in.close();
			out.flush();
			out.close();
			return ;
		}
		for (File file : srcDir.listFiles()) {
			if(file.getAbsolutePath().equals(zipfile)){
				// 避免死循环，自己压缩自己。
				continue;
			}
			if (file.isDirectory()) {
				if(basePath != null){
					zipFile(out, zipfile, file
							, basePath + File.separator + file.getName());
				} else {
					zipFile(out, zipfile, file, file.getName());
				}
				continue;
			}
			FileInputStream in = new FileInputStream(file);
			if(basePath != null){
				out.putNextEntry(new ZipEntry(basePath + File.separator + file.getName()));
			} else {
				out.putNextEntry(new ZipEntry(file.getName()));
			}
			byte[] b = new byte[1024];
			int byteread = 0;
			int bytesum = 0;
			int off = 0;
			while ((byteread = in.read(b, off, 1024)) != -1) {
				bytesum += byteread; // 字节数 文件大小
				out.write(b, 0, byteread);
			}
			in.close();
		}
		out.flush();
		out.close();
	}
}
